package com.tencent.welink.api;
import com.alibaba.fastjson.JSONObject;
import com.tencent.welink.config.BussinessConfig;
import com.tencent.welink.util.HttpPoolUtils;
import com.tencent.welink.util.HttpSigUtil;
import com.tencent.welink.util.TicketData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by junchihe on 2019/7/30.
 */
public class OpenApiTokenChange implements Runnable{
    private static final Logger log = LogManager.getLogger(OpenApiTokenChange.class);
    private static TicketData ticketData = null;
    private static final Object lock = new Object();

    private static void getLoginByAppURL() {
        try {
            long time = System.currentTimeMillis();
            long num = (long) (Math.random() * 1000 + 1);
            String sig = HttpSigUtil.encrypt(BussinessConfig.appKey, time, num);
            String url = BussinessConfig.httpProtocal + BussinessConfig.httpDomain + BussinessConfig.loginByapp + "?appid=" + BussinessConfig.appId + "&time=" + time + "&num=" + num + "&sig=" + sig +
                    "&app_ticket=" +
                    BussinessConfig.appTicket;
            String result = HttpPoolUtils.httpGet(url,null);
            JSONObject jsonObject = JSONObject.parseObject(result);

            log.info("update ticket Url: {}", url);
            log.info("update ticket result: " + result);
            if (jsonObject.containsKey("code") && 0 == jsonObject.getIntValue("code")) {
                JSONObject data = jsonObject.getJSONObject("data");
                ticketData = new TicketData();
                ticketData.iotim_ticket = data.getString("iotim_ticket");
                ticketData.token = data.getString("token");
                ticketData.time = System.currentTimeMillis();
            } else {
                log.error("update ticket loginByAPPError：" + result);

            }
        }catch (Exception e) {
            //ticketData = null;
            log.error(e);
        }

    }

    public static  TicketData getTicketData() {
        if(ticketData != null && System.currentTimeMillis() - ticketData.time < BussinessConfig.loginDurationMinutes) {
            return ticketData;
        }

        synchronized (lock) {
            if(ticketData != null && System.currentTimeMillis() - ticketData.time < BussinessConfig.loginDurationMinutes) {
                return ticketData;
            }
            getLoginByAppURL();
            return ticketData;
        }

    }


  public void run() {
      synchronized (lock) {
          getLoginByAppURL();
      }
  }
}
